package admin

import (
	"ecms/models"
	"ecms/utils/hash"
	"ecms/utils/repository"
	"ecms/utils/response"
	"ecms/utils/validator"
	"github.com/gin-gonic/gin"
)

type LoginController struct {
}

// Password 账号密码登录
func (l *LoginController) Password(ctx *gin.Context) {
	reqData := make(map[string]string)
	rules := validator.NewRules(
		validator.NewRule("account", "账号", true, validator.TypeAlpha),
		validator.NewRule("password", "密码", true, validator.TypePassword),
	)
	if !validator.ShouldBindMapFromPostForm(ctx, &reqData, rules...) {
		return
	}

	hasUser := &models.AdminMember{}
	repo := repository.New(&models.AdminMember{})
	if !repo.FindByField("username", reqData["account"], hasUser) || hasUser.Id == 0 {
		response.FailJson(ctx, "账号或密码错误", nil)
		return
	}

	if !hash.PasswordVerify(reqData["password"], hasUser.Password) {
		response.FailJson(ctx, "账号或密码错误", nil)
		return
	}

	token, err := hash.EncryptAdminAccessToken(*hasUser)
	if err != nil {
		response.FailJson(ctx, "登录失败, 请稍后再试", nil)
		return
	}

	response.SuccessJson(ctx, "登录成功", struct {
		Token string `json:"token"`
	}{
		Token: token,
	})
}
